package br.ucb.rest.controle.servlet.impl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.ucb.rest.controle.servlet.AbstractServlet;
import br.ucb.rest.negocio.impl.CardapioBOS;
import br.ucb.rest.negocio.impl.IngredienteBOS;
import br.ucb.rest.util.TradutorXML;

@WebServlet(urlPatterns={"/cardapio"})
public class CardapioServlet extends AbstractServlet {
	private static final long serialVersionUID = 1L;

	public void listarPorCategoria(HttpServletRequest request, HttpServletResponse response) {
		try {
			
			CardapioBOS bos = CardapioBOS.getInstance();
			
			Integer nuCategoria = Integer.valueOf(request.getParameter("nuCategoria"));
			
			String retorno = TradutorXML.getInstance().traduzirListaCardapio(bos.recuperarPorCategoria(nuCategoria));
			
			prepararResposta(response);
			response.setContentLength(retorno.getBytes().length);
			response.getOutputStream().write(retorno.getBytes());
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void recuperarFoto(HttpServletRequest request, HttpServletResponse response) {
		try {
			
			CardapioBOS bos = CardapioBOS.getInstance();
			
			Integer nuCardapio = Integer.valueOf(request.getParameter("nuCardapio"));
			
			byte[] retorno = bos.recuperarFoto(nuCardapio);
			
			response.setContentType("image/jpg");
			response.setContentLength(retorno.length);
			response.getOutputStream().write(retorno);
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void listarIngredientes(HttpServletRequest request, HttpServletResponse response) {
		try {
			IngredienteBOS bos = IngredienteBOS.getInstance();
			
			Integer nuCardapio = Integer.valueOf(request.getParameter("nuCardapio"));
			
			String retorno = TradutorXML.getInstance().traduzirListaIngrediente(bos.listarIngredientesPorCardapio(nuCardapio));
			if (retorno != null) {
				prepararResposta(response);
				response.setContentLength(retorno.getBytes().length);
				response.getOutputStream().write(retorno.getBytes());
			}
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void recuperarCardapio(HttpServletRequest request, HttpServletResponse response) {
		try {
			Integer nuCardapio = Integer.valueOf(request.getParameter("nuCardapio"));
			
			String retorno = TradutorXML.getInstance().traduzirCardapio(CardapioBOS.getInstance().recuperarPorId(nuCardapio), null);
			
			prepararResposta(response);
			response.setContentLength(retorno.getBytes().length);
			response.getOutputStream().write(retorno.getBytes());
			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
